package com.draemoncode.weixindb.event;

import com.draemoncode.weixindb.constant.MessagePackageTypeConstant;
import com.draemoncode.weixindb.constant.XiazhuFieldConstant;
import com.draemoncode.weixindb.conventer.CMessagePackageConventer;
import com.draemoncode.weixindb.domain.B_XiaZhu;
import com.draemoncode.weixindb.server.CMessagePackage;
import com.draemoncode.weixindb.server.IEvent;
import com.draemoncode.weixindb.service.BusiService;
import com.draemoncode.weixindb.util.JSONUtil;
import com.draemoncode.weixindb.util.ValueUtil;
import com.draemoncode.weixindb.websocket.UIMessage;
import com.draemoncode.weixindb.websocket.UISession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * 第2步 下注
 * @author yangz
 * @date 2017/4/9
 *
 */
@Component
@Slf4j
public class XiaZhuEvent implements IEvent<B_XiaZhu, Object> {

    @Autowired
    private BusiService busiService;

    @Override
    public Boolean shoudProcess(CMessagePackage b_csmessage) {
        if(MessagePackageTypeConstant.REQUEST_XIA_ZHU.equals(b_csmessage.getType())){
            return true;
        }
        return false;
    }

    @Override
    public B_XiaZhu busiExec(CMessagePackage cMessagePackage) {
        Integer podId = cMessagePackage.getSyncid();
        String username = ValueUtil.toString(cMessagePackage.getMsg().get(XiazhuFieldConstant.REQUEST_USER_NAME));
        BigDecimal zhu = ValueUtil.toBigDecimal(cMessagePackage.getMsg().get(XiazhuFieldConstant.REQUEST_ZHU));
        B_XiaZhu b_xiaZhu = busiService.xiaZhu(podId, username, zhu);
        return b_xiaZhu;
    }

    @Override
    public Object uiExec(CMessagePackage cMessagePackage, B_XiaZhu busiResult) {
        UIMessage uiMessage = CMessagePackageConventer.toUIMessage(cMessagePackage);
        uiMessage.setPodId(busiResult.getId());
        uiMessage.setMsg(JSONUtil.toMap(busiResult));
        UISession.send(uiMessage);
        return null;
    }

    @Override
    public CMessagePackage buildResponse(CMessagePackage cMessagePackage, B_XiaZhu busiResult, Object uiResult) {
        CMessagePackage response = new CMessagePackage(MessagePackageTypeConstant.RESPONSE_RECEIVE);
        response.setSyncid(busiResult.getPod_id());
        return response;
    }

}
